package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;

/**
 * 用户服务
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    /**
     * 查询所有角色
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取分页查询条件
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        //使用分页插件分页
        PageHelper.startPage(currentPage, pageSize);
        Page<Role> page = roleDao.findPage();
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询所有角色权限
     *
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return roleDao.findAll();
    }

    /**
     * 根据id查询角色权限
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findPermissionIdsByCheckRoleId(Integer id) {
        return roleDao.findPermissionIdsByCheckRoleId(id);
    }

    /**
     * 添加权限
     *
     * @param
     * @return
     */
    @Override
    public void add(Integer[] permissionIds, Integer roleId) {
        //删除角色表和权限表的关联
        roleDao.deleteById(roleId);
        //便利获取所有选定权限id
        for (Integer permissionId : permissionIds) {
            //将角色id和权限id添加到map集合中
            HashMap<String, Integer> hm = new HashMap<>();
            hm.put("roleId", roleId);
            hm.put("permissionId", permissionId);

            //添加角色表和权限表的关联
            roleDao.add(hm);
        }
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @Override
    public void delete(Integer roleId) {
        if (roleId!=null){
            //删除角色和权限的关联
            roleDao.deleteById(roleId);
            //删除角色
            roleDao.delete(roleId);
        }

    }

    @Override
    public List<Role> findRole() {
        return roleDao.findRole();
    }




}
